package com.john.http.core.convert;


import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 〈一句话功能简述〉<br/>
 * 〈中国式的时间单位转换类〉
 *
 * @author jiangguangtao on 2016/5/20.
 */
public class ChinaTimeUnitConverter implements IValueConverter {
    private static Pattern TIME_PATTERN = Pattern.compile("^(?<num>[1-9]\\d*)(?<unit>.+)");
    private static Map<String, Integer> unitTimes = new HashMap<>(5);

    static {
        unitTimes.put("分", 1);
        unitTimes.put("分钟", 1);
        unitTimes.put("小时", 60);
        unitTimes.put("时", 60);
        unitTimes.put("天", 1440);
    }

    @Override
    public String getName() {
        return "中文时间单位转换";
    }

    @Override
    public Object convert(String str) {
        //3天
        //12小时
        //35分钟
        Long val = 0L;
        Matcher matcher = TIME_PATTERN.matcher(str);
        if (matcher.matches()) {
            String g1 = matcher.group("num");
            String g2 = matcher.group("unit");
            Long tempVal = Long.valueOf(g1);
            int times = 1;
            if (unitTimes.containsKey(g2)) {
                times = unitTimes.get(g2);
            }
            val = tempVal * times;
        }
        return val;
    }
}
